import React from 'react';
import { Card, Table, Checkbox, Space, Select, Button } from 'antd';
import { SaveOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Option } = Select;

// 模拟权限数据
interface PermissionRecord {
  key: string;
  resource: string;
  operation: string;
  description: string;
  allowedRoles: string[];
}

const permissionData: PermissionRecord[] = [
  { 
    key: '1', 
    resource: '用户管理', 
    operation: '查看', 
    description: '查看用户列表和详情', 
    allowedRoles: ['超级管理员', '管理员', '编辑']
  },
  { 
    key: '2', 
    resource: '用户管理', 
    operation: '添加', 
    description: '添加新用户', 
    allowedRoles: ['超级管理员', '管理员']
  },
  { 
    key: '3', 
    resource: '用户管理', 
    operation: '编辑', 
    description: '编辑用户信息', 
    allowedRoles: ['超级管理员', '管理员']
  },
  { 
    key: '4', 
    resource: '用户管理', 
    operation: '删除', 
    description: '删除用户', 
    allowedRoles: ['超级管理员']
  },
  { 
    key: '5', 
    resource: '角色管理', 
    operation: '查看', 
    description: '查看角色列表和详情', 
    allowedRoles: ['超级管理员', '管理员', '编辑']
  },
  { 
    key: '6', 
    resource: '角色管理', 
    operation: '添加', 
    description: '添加新角色', 
    allowedRoles: ['超级管理员', '管理员']
  },
  { 
    key: '7', 
    resource: '角色管理', 
    operation: '编辑', 
    description: '编辑角色信息', 
    allowedRoles: ['超级管理员', '管理员']
  },
  { 
    key: '8', 
    resource: '角色管理', 
    operation: '删除', 
    description: '删除角色', 
    allowedRoles: ['超级管理员']
  },
];

// 角色列表
const roles = ['超级管理员', '管理员', '编辑', '普通用户', '访客'];

const PermissionManagement: React.FC = () => {
  // 权限数据状态
  const [permissions, setPermissions] = React.useState<PermissionRecord[]>(permissionData);
  // 选择的角色
  const [selectedRole, setSelectedRole] = React.useState<string>('');
  // 选择的权限资源
  const [selectedResource, setSelectedResource] = React.useState<string>('全部');
  
  // 资源列表
  const resources = ['全部', ...Array.from(new Set(permissions.map(item => item.resource)))];
  
  // 处理角色选择
  const handleRoleChange = (value: string) => {
    setSelectedRole(value);
  };
  
  // 处理资源选择
  const handleResourceChange = (value: string) => {
    setSelectedResource(value);
  };
  
  // 处理权限变更
  const handlePermissionChange = (checked: boolean, permissionKey: string, roleName: string) => {
    const updatedPermissions = permissions.map(permission => {
      if (permission.key === permissionKey) {
        if (checked) {
          return {
            ...permission,
            allowedRoles: [...permission.allowedRoles, roleName]
          };
        } else {
          return {
            ...permission,
            allowedRoles: permission.allowedRoles.filter(role => role !== roleName)
          };
        }
      }
      return permission;
    });
    setPermissions(updatedPermissions);
  };
  
  // 保存权限配置
  const handleSave = () => {
    console.log('保存权限配置:', permissions);
    // 实际应用中这里会调用API保存权限配置
  };
  
  // 过滤权限数据
  const filteredPermissions = selectedResource === '全部' 
    ? permissions 
    : permissions.filter(item => item.resource === selectedResource);
  
  // 表格列配置
  const columns: ColumnsType<PermissionRecord> = [
    { title: '资源', dataIndex: 'resource', key: 'resource' },
    { title: '操作', dataIndex: 'operation', key: 'operation' },
    { title: '描述', dataIndex: 'description', key: 'description' },
    { 
      title: '权限配置', 
      key: 'permissions', 
      render: (_, record) => (
        <div>
          {selectedRole ? (
            <Checkbox 
              checked={record.allowedRoles.includes(selectedRole)}
              onChange={(e) => handlePermissionChange(e.target.checked, record.key, selectedRole)}
            >
              {selectedRole} 允许此操作
            </Checkbox>
          ) : (
            <span style={{ color: '#999' }}>请先选择角色</span>
          )}
        </div>
      )
    },
    { 
      title: '当前权限', 
      key: 'currentPermissions', 
      render: (_, record) => (
        <span>{record.allowedRoles.join('、') || '无'}</span>
      )
    },
  ];

  return (
    <div>
      <h1 style={{ marginBottom: '24px' }}>权限管理</h1>
      <Card variant="outlined" extra={
        <Button 
          type="primary" 
          icon={<SaveOutlined />} 
          onClick={handleSave}
          disabled={!selectedRole}
        >
          保存配置
        </Button>
      }>
        <Space style={{ marginBottom: 16 }}>
          <span>选择角色：</span>
          <Select 
            placeholder="请选择角色"
            style={{ width: 150 }}
            onChange={handleRoleChange}
            value={selectedRole}
          >
            {roles.map(role => (
              <Option key={role} value={role}>{role}</Option>
            ))}
          </Select>
          <span style={{ marginLeft: 16 }}>选择资源：</span>
          <Select 
            style={{ width: 150 }}
            onChange={handleResourceChange}
            value={selectedResource}
          >
            {resources.map(resource => (
              <Option key={resource} value={resource}>{resource}</Option>
            ))}
          </Select>
        </Space>
        <Table 
          columns={columns} 
          dataSource={filteredPermissions} 
          pagination={{ pageSize: 10 }}
          rowKey="key"
        />
      </Card>
    </div>
  );
};

export default PermissionManagement;